const http = require("http");
const fs = require("fs");
const qs = require("querystring");
const server = http.createServer();
server.listen(3000, () => {
  console.log("http://localhost:3000端口已启动");
});

server.on("request", (req, res) => {
  res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
  let s = req.url.split("?")[1];
  let user = qs.parse(s);
  if (req.url.startsWith("/login")) {
    let persons = fs.readFileSync("persons.json", "utf-8");
    persons = JSON.parse(persons);

    let u = persons.findIndex(
      (item) =>
        item.username === user.username && item.password === user.password
    );

    if (u != -1) {
      res.end("登录成功");
    } else {
      res.end("用户名或密码错误");
    }
  } else if (req.url.startsWith("/register")) {
    let rest = fs.readFileSync("persons.json", "utf-8");
    let obj = JSON.parse(rest);
    if (obj.find((item) => item.username == user.username)) {
      res.end("该用户已注册");
    } else {
      obj = [...obj, user];
      res.end("注册成功");
      let obj1 = JSON.stringify(obj);
      fs.writeFileSync("persons.json", obj1);
    }
  } else {
    res.end(fs.readFileSync("./views/404.html"));
  }
});
